package main_form

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
)

type WidgetsProperty struct {
	Key   string `xml:"Key,attr"`
	Value string `xml:"Value,attr"`
}

type WidgetAtt struct {
	XMLName    xml.Name
	Attributes map[string]string `xml:"-"`
	Properties []Property        `xml:"Property"`
	// Add additional fields here based on the expected attributes or child elements
}

func (w *WidgetAtt) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	if nil == w.Attributes {
		w.Attributes = map[string]string{}
	}
	for _, attr := range start.Attr {
		w.Attributes[attr.Name.Local] = attr.Value
	}
	type widgetAttAlias WidgetAtt // 别名，以避免无限递归调用
	return d.DecodeElement((*widgetAttAlias)(w), &start)
}

// SceneSkin 皮肤模板
type SceneSkin struct {
	XMLName xml.Name    `xml:"root"`
	Widgets []WidgetAtt `xml:",any"`
}

var AllSceneSkin = map[string]*SceneSkin{}

func LoadSkinConfig(filename string) (*SceneSkin, error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	conf, err := loadSkinConfigFromData(data)
	if err != nil {
		return nil, err
	}
	AllSceneSkin[filename] = conf
	return conf, nil
}

func loadSkinConfigFromData(data []byte) (*SceneSkin, error) {
	var config SceneSkin
	err := xml.Unmarshal([]byte(data), &config)
	if err != nil {
		fmt.Println("Error:", err)
		return nil, err
	}
	return &config, nil
}
